"use client"

import type React from "react"

import { useState } from "react"

// 菜单项类型定义
interface MenuItem {
  id: number
  name: string
  path: string
  icon: string
  parentId: null // 当前系统中所有菜单都是顶级菜单，parentId 固定为 null
  sort: number
  status: string
  visible: boolean
  permissions: string[]
  description: string
  createdAt: string
  children: never[] // 扁平化结构，children 始终为空数组
}
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Plus, Search, Edit, Trash2, MoreHorizontal, MenuIcon, ChevronRight, ChevronDown } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Switch } from "@/components/ui/switch"

// 模拟菜单数据 - 优化后的扁平化结构
const mockMenus: MenuItem[] = [
  {
    id: 1,
    name: "仪表盘",
    path: "/admin",
    icon: "Home",
    parentId: null,
    sort: 1,
    status: "active",
    visible: true,
    permissions: ["dashboard:read"],
    description: "系统仪表盘页面",
    createdAt: "2024-01-15",
    children: [],
  },
  {
    id: 2,
    name: "用户管理",
    path: "/admin/users",
    icon: "Users",
    parentId: null,
    sort: 2,
    status: "active",
    visible: true,
    permissions: ["user:read"],
    description: "用户账户管理",
    createdAt: "2024-01-15",
    children: [],
  },
  {
    id: 3,
    name: "角色管理",
    path: "/admin/roles",
    icon: "Shield",
    parentId: null,
    sort: 3,
    status: "active",
    visible: true,
    permissions: ["role:read"],
    description: "角色权限管理",
    createdAt: "2024-01-16",
    children: [],
  },
  {
    id: 4,
    name: "权限管理",
    path: "/admin/permissions",
    icon: "Key",
    parentId: null,
    sort: 4,
    status: "active",
    visible: true,
    permissions: ["permission:read"],
    description: "权限节点管理",
    createdAt: "2024-01-17",
    children: [],
  },
  {
    id: 5,
    name: "菜单管理",
    path: "/admin/menus",
    icon: "MenuIcon",
    parentId: null,
    sort: 5,
    status: "active",
    visible: true,
    permissions: ["menu:read"],
    description: "系统菜单管理",
    createdAt: "2024-01-18",
    children: [],
  },
  {
    id: 6,
    name: "统计报表",
    path: "/admin/reports",
    icon: "BarChart3",
    parentId: null,
    sort: 6,
    status: "active",
    visible: true,
    permissions: ["report:read"],
    description: "数据统计报表",
    createdAt: "2024-01-19",
    children: [],
  },
  {
    id: 7,
    name: "系统设置",
    path: "/admin/settings",
    icon: "Settings",
    parentId: null,
    sort: 7,
    status: "active",
    visible: true,
    permissions: ["settings:read"],
    description: "系统配置管理",
    createdAt: "2024-01-20",
    children: [],
  },
]

const iconOptions = [
  "Home",
  "Users",
  "Shield",
  "Key",
  "MenuIcon",
  "Settings",
  "BarChart3",
  "FileText",
  "Database",
  "Globe",
  "Mail",
  "Phone",
]

export default function MenusPage() {
  const [menus, setMenus] = useState<MenuItem[]>(mockMenus)
  const [searchTerm, setSearchTerm] = useState("")
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedMenu, setSelectedMenu] = useState<MenuItem | null>(null)
  const [expandedMenus, setExpandedMenus] = useState<number[]>([2])
  const [newMenu, setNewMenu] = useState({
    name: "",
    path: "",
    icon: "Home", // Updated default value
    parentId: null as null, // 明确指定为 null 类型
    sort: 1,
    visible: true,
    permissions: [] as string[],
    description: "",
  })

  const filteredMenus = menus.filter(
    (menu) =>
      menu.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      menu.path.toLowerCase().includes(searchTerm.toLowerCase()) ||
      menu.description.toLowerCase().includes(searchTerm.toLowerCase()),
  )

  const buildMenuTree = (menus: MenuItem[], parentId: null = null): MenuItem[] => {
    return menus
      .filter((menu) => menu.parentId === parentId)
      .sort((a, b) => a.sort - b.sort)
      .map((menu) => ({
        ...menu,
        children: [], // 扁平化结构，不需要递归构建子菜单
      }))
  }

  const menuTree = buildMenuTree(filteredMenus)

  const handleAddMenu = () => {
    const menu: MenuItem = {
      id: menus.length + 1,
      ...newMenu,
      status: "active",
      createdAt: new Date().toISOString().split("T")[0],
      children: [],
    }
    setMenus([...menus, menu])
    setNewMenu({
      name: "",
      path: "",
      icon: "Home", // Updated default value
      parentId: null as null,
      sort: 1,
      visible: true,
      permissions: [],
      description: "",
    })
    setIsAddDialogOpen(false)
  }

  const handleEditMenu = () => {
    setMenus(menus.map((menu) => (menu.id === selectedMenu.id ? { ...menu, ...selectedMenu } : menu)))
    setIsEditDialogOpen(false)
    setSelectedMenu(null)
  }

  const handleDeleteMenu = (id: number) => {
    setMenus(menus.filter((menu) => menu.id !== id && menu.parentId !== id))
  }

  const toggleExpanded = (menuId: number) => {
    setExpandedMenus((prev) => (prev.includes(menuId) ? prev.filter((id) => id !== menuId) : [...prev, menuId]))
  }

  const getStatusBadge = (status: string) => {
    return status === "active" ? (
      <Badge variant="default" className="text-background bg-foreground">
        启用
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-gray-100 text-gray-800">
        禁用
      </Badge>
    )
  }

  const renderMenuTree = (menus: any[], level = 0): React.ReactNode[] => {
    const result: React.ReactNode[] = []

    menus.forEach((menu) => {
      result.push(
        <TableRow key={menu.id}>
          <TableCell>
            <div className="flex items-center" style={{ paddingLeft: `${level * 20}px` }}>
              {menu.children.length > 0 && (
                <Button variant="ghost" size="sm" className="h-4 w-4 p-0 mr-2" onClick={() => toggleExpanded(menu.id)}>
                  {expandedMenus.includes(menu.id) ? (
                    <ChevronDown className="h-3 w-3" />
                  ) : (
                    <ChevronRight className="h-3 w-3" />
                  )}
                </Button>
              )}
              <MenuIcon className="mr-2 h-4 w-4 text-primary" />
              <span className="font-medium">{menu.name}</span>
            </div>
          </TableCell>
          <TableCell>
            <Badge variant="outline">{menu.path}</Badge>
          </TableCell>
          <TableCell>{menu.icon}</TableCell>
          <TableCell>{menu.sort}</TableCell>
          <TableCell>
            <Badge variant={menu.visible ? "default" : "secondary"}>{menu.visible ? "显示" : "隐藏"}</Badge>
          </TableCell>
          <TableCell>
            <div className="flex flex-wrap gap-1">
              {menu.permissions.slice(0, 2).map((permission: string) => (
                <Badge key={permission} variant="outline" className="text-xs">
                  {permission}
                </Badge>
              ))}
              {menu.permissions.length > 2 && (
                <Badge variant="outline" className="text-xs">
                  +{menu.permissions.length - 2}
                </Badge>
              )}
            </div>
          </TableCell>
          <TableCell>{getStatusBadge(menu.status)}</TableCell>
          <TableCell className="text-right">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                  <span className="sr-only">打开菜单</span>
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() => {
                    setSelectedMenu(menu)
                    setIsEditDialogOpen(true)
                  }}
                >
                  <Edit className="mr-2 h-4 w-4" />
                  编辑
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleDeleteMenu(menu.id)} className="text-destructive">
                  <Trash2 className="mr-2 h-4 w-4" />
                  删除
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </TableCell>
        </TableRow>,
      )

      if (expandedMenus.includes(menu.id) && menu.children.length > 0) {
        result.push(...renderMenuTree(menu.children, level + 1))
      }
    })

    return result
  }

  const parentMenuOptions = menus.filter((menu) => menu.parentId === null)

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight">菜单管理</h2>
          <p className="text-muted-foreground">管理系统菜单结构和导航</p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              添加菜单
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>添加新菜单</DialogTitle>
              <DialogDescription>创建一个新的系统菜单项</DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  菜单名称
                </Label>
                <Input
                  id="name"
                  value={newMenu.name}
                  onChange={(e) => setNewMenu({ ...newMenu, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="path" className="text-right">
                  菜单路径
                </Label>
                <Input
                  id="path"
                  value={newMenu.path}
                  onChange={(e) => setNewMenu({ ...newMenu, path: e.target.value })}
                  className="col-span-3"
                  placeholder="例如: /users"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="icon" className="text-right">
                  图标
                </Label>
                <Select value={newMenu.icon} onValueChange={(value) => setNewMenu({ ...newMenu, icon: value })}>
                  <SelectTrigger className="col-span-3">
                    <SelectValue placeholder="选择图标" />
                  </SelectTrigger>
                  <SelectContent>
                    {iconOptions.map((icon) => (
                      <SelectItem key={icon} value={icon}>
                        {icon}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="parent" className="text-right">
                  父级菜单
                </Label>
                <Select
                  value={newMenu.parentId?.toString() || "none"}
                  onValueChange={(value) =>
                    setNewMenu({ ...newMenu, parentId: value === "none" ? null : Number.parseInt(value) })
                  }
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue placeholder="选择父级菜单（可选）" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">无父级菜单</SelectItem>
                    {parentMenuOptions.map((menu) => (
                      <SelectItem key={menu.id} value={menu.id.toString()}>
                        {menu.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="sort" className="text-right">
                  排序
                </Label>
                <Input
                  id="sort"
                  type="number"
                  value={newMenu.sort}
                  onChange={(e) => setNewMenu({ ...newMenu, sort: Number.parseInt(e.target.value) || 1 })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="visible" className="text-right">
                  是否显示
                </Label>
                <div className="col-span-3">
                  <Switch
                    id="visible"
                    checked={newMenu.visible}
                    onCheckedChange={(checked) => setNewMenu({ ...newMenu, visible: checked })}
                  />
                </div>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="description"
                  value={newMenu.description}
                  onChange={(e) => setNewMenu({ ...newMenu, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" onClick={handleAddMenu}>
                创建菜单
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <Tabs defaultValue="tree" className="space-y-4">
        <TabsList>
          <TabsTrigger value="tree">菜单树</TabsTrigger>
          <TabsTrigger value="list">菜单列表</TabsTrigger>
        </TabsList>

        <TabsContent value="tree" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>菜单树结构</CardTitle>
              <CardDescription>系统菜单的层级结构展示</CardDescription>
              <div className="flex items-center space-x-2">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索菜单..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-8"
                  />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>菜单名称</TableHead>
                    <TableHead>路径</TableHead>
                    <TableHead>图标</TableHead>
                    <TableHead>排序</TableHead>
                    <TableHead>显示状态</TableHead>
                    <TableHead>权限要求</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>{renderMenuTree(menuTree)}</TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="list" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>菜单列表</CardTitle>
              <CardDescription>系统中所有菜单项的详细信息</CardDescription>
              <div className="flex items-center space-x-2">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索菜单..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-8"
                  />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>菜单名称</TableHead>
                    <TableHead>路径</TableHead>
                    <TableHead>图标</TableHead>
                    <TableHead>父级菜单</TableHead>
                    <TableHead>排序</TableHead>
                    <TableHead>显示状态</TableHead>
                    <TableHead>权限要求</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredMenus.map((menu) => (
                    <TableRow key={menu.id}>
                      <TableCell className="font-medium">
                        <div className="flex items-center">
                          <MenuIcon className="mr-2 h-4 w-4 text-primary" />
                          {menu.name}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{menu.path}</Badge>
                      </TableCell>
                      <TableCell>{menu.icon}</TableCell>
                      <TableCell>
                        {menu.parentId ? (
                          <Badge variant="secondary">{menus.find((m) => m.id === menu.parentId)?.name || "未知"}</Badge>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell>{menu.sort}</TableCell>
                      <TableCell>
                        <Badge variant={menu.visible ? "default" : "secondary"}>{menu.visible ? "显示" : "隐藏"}</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {menu.permissions.slice(0, 2).map((permission) => (
                            <Badge key={permission} variant="outline" className="text-xs">
                              {permission}
                            </Badge>
                          ))}
                          {menu.permissions.length > 2 && (
                            <Badge variant="outline" className="text-xs">
                              +{menu.permissions.length - 2}
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>{getStatusBadge(menu.status)}</TableCell>
                      <TableCell>{menu.createdAt}</TableCell>
                      <TableCell className="text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0">
                              <span className="sr-only">打开菜单</span>
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => {
                                setSelectedMenu(menu)
                                setIsEditDialogOpen(true)
                              }}
                            >
                              <Edit className="mr-2 h-4 w-4" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => handleDeleteMenu(menu.id)} className="text-destructive">
                              <Trash2 className="mr-2 h-4 w-4" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 编辑菜单对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>编辑菜单</DialogTitle>
            <DialogDescription>修改菜单信息和配置</DialogDescription>
          </DialogHeader>
          {selectedMenu && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-name" className="text-right">
                  菜单名称
                </Label>
                <Input
                  id="edit-name"
                  value={selectedMenu.name}
                  onChange={(e) => setSelectedMenu({ ...selectedMenu, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-path" className="text-right">
                  菜单路径
                </Label>
                <Input
                  id="edit-path"
                  value={selectedMenu.path}
                  onChange={(e) => setSelectedMenu({ ...selectedMenu, path: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-icon" className="text-right">
                  图标
                </Label>
                <Select
                  value={selectedMenu.icon}
                  onValueChange={(value) => setSelectedMenu({ ...selectedMenu, icon: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {iconOptions.map((icon) => (
                      <SelectItem key={icon} value={icon}>
                        {icon}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-parent" className="text-right">
                  父级菜单
                </Label>
                <Select
                  value={selectedMenu.parentId?.toString() || "none"}
                  onValueChange={(value) =>
                    setSelectedMenu({ ...selectedMenu, parentId: value === "none" ? null : Number.parseInt(value) })
                  }
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">无父级菜单</SelectItem>
                    {parentMenuOptions
                      .filter((menu) => menu.id !== selectedMenu.id)
                      .map((menu) => (
                        <SelectItem key={menu.id} value={menu.id.toString()}>
                          {menu.name}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-sort" className="text-right">
                  排序
                </Label>
                <Input
                  id="edit-sort"
                  type="number"
                  value={selectedMenu.sort}
                  onChange={(e) => setSelectedMenu({ ...selectedMenu, sort: Number.parseInt(e.target.value) || 1 })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-visible" className="text-right">
                  是否显示
                </Label>
                <div className="col-span-3">
                  <Switch
                    id="edit-visible"
                    checked={selectedMenu.visible}
                    onCheckedChange={(checked) => setSelectedMenu({ ...selectedMenu, visible: checked })}
                  />
                </div>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="edit-description"
                  value={selectedMenu.description}
                  onChange={(e) => setSelectedMenu({ ...selectedMenu, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button type="submit" onClick={handleEditMenu}>
              保存更改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
